package org.apache.ocean.util;

import java.awt.geom.Rectangle2D;
import java.text.DecimalFormat;
import org.geotools.referencing.datum.DefaultEllipsoid;

public class DistanceUtils {
  
  private static final int coordPrime = 100000000;
  private static final String coordPad = "000000000000";
  
  private static DefaultEllipsoid de = DefaultEllipsoid.WGS84;
  
  public static double orthodromicDistance(double x1, double y1, double x2, double y2) {
    return de.orthodromicDistance(x1, y1, x2, y2);
  }
  
  public static double getDistanceMi(double x1, double y1, double x2, double y2) {
    return (orthodromicDistance(x1, y1, x2, y2) *0.621371) / 1000;
  }
  
  /**
   *
   * @param x1
   * @param y1
   * @param miles
   * @return boundary rectangle where getY/getX is top left, getMinY/getMinX is bottom right
   */
  public static Rectangle2D getBoundary(double x1, double y1, double miles) {
    return LonLatTrig.getRadiusBoundsMi(y1, x1, miles);
  }
  
  public static Rectangle2D getBoundaryMi(double x1, double y1, double miles){
    return LonLatTrig.getRadiusBoundsMi(y1, x1, miles);
  }
  
  public static Rectangle2D getBoundaryKm(double x1, double y1, double km){
    return LonLatTrig.getRadiusBoundsKm(y1, x1, km);
  }
  
  /**
   * convert a padded longitude coord to a double
   * @param s
   * @return
   */
  public static double stringToLng(String s){
    double x = stringToCood(s);
    return x - 180;
  }
  
  /**
   * convert a padded latitude coord to a double
   * @param s
   * @return
   */
  public static double stringToLat(String s ){
    double x = stringToCood(s);
    return x - 360;
  }
  
  private static double stringToCood(String s){
    double x;
    try {
      x = new Double(s).doubleValue();
    } catch (Exception e){
      return 0;
    }
    return x / coordPrime;
  }
  
  /**
   * convert a longitude to a padded string for searching
   * @param cord
   * @return
   */
  public static String lngToString(double cord) {
    double x = cord + 180;
    return coordToString(x);
  }
  
  /**
   * convert a latitude to a padded string for searching
   * @param cord
   * @return
   */
  public static String latToString(double cord){
    double x = cord + 360;
    return coordToString(x);
  }
  
  private static  String coordToString(double coord){
    double x = coord * coordPrime;
    DecimalFormat df  = new DecimalFormat(coordPad);
    return df.format(x);
  }
  
}
